<template>
  <div class="y-table">
    <el-form
      :model="model"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-table
        :data="data"
        :stripe="stripe"
        :border="border"
        :size="size"
        :show-header="showHeader"
      >
        <el-table-column
          :label="item.label"
          :width="item.width"
          v-for="(item, index) of list"
          :key="index"
        >
          <el-form-item
            :prop="`data.${$index}.${item.prop}`"
            :rules="item.rules"
            slot-scope="{ row, $index }"
          >
            <template v-if="item.type">
              <component
                v-on="$listeners"
                @change="handleChange(item, row)"
                :modelValue="row[item.prop]"
                @modelInput="
                  (value) => {
                    modelInput(row, item, value);
                  }
                "
                :formModel="row"
                :item="item"
                :is="isComponent(item, row)"
              >
                <template slot-scope="{ self, model, formModel }">
                  <slot :self="self" :model="row" :formModel="formModel"></slot>
                </template>
              </component>
            </template>
            <span v-else>
              {{ row[item.prop] }}
            </span>
          </el-form-item>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>
<script>
import { modules } from "../y-form/component";
export default {
  props: {
    options: {
      type: Object,
      default: () => {},
    },
    data: {
      type: Array,
      default: () => {},
    },
  },
  data() {
    let self = this;
    return {
      modules,
      self,
    };
  },
  name: "yTable",
  computed: {
    isComponent() {
      return (item) => {
        let module = this.modules.find((c) =>
          c.includesComponent.includes(item.type)
        );
        return module ? module.component : "";
      };
    },
    model() {
      return {
        data: this.data,
      };
    },
    list() {
      return this.options.list;
    },
    stripe() {
      return this.options.stripe;
    },
    border() {
      return this.options.border;
    },
    size() {
      return this.options.size;
    },
    showHeader() {
      return this.options.showHeader;
    },
  },
  methods: {
    /**
     * 表单改变事件
     * @param {Objec} props
     */
    handleChange(it, row) {
      this.$emit("formChange", {
        value: row[it.prop],
        model: row,
        options: it,
      });
    },
    /**
     * @description: 函数描述
     * @param {*} row
     * @param {*} item
     * @param {*} value
     * @return {*}
     */
    modelInput(row, item, value) {
      this.$set(row, item.prop, value);
    },
  },
};
</script>

<style lang="scss">
.y-table {
  .el-form-item,
  .el-form-item__content {
    margin: 0 !important;
  }
}
</style>